import logging
import os
import zipfile

from hostcmdtools.HostCmdTool import HostCmdTool
from tools.file_tool import FileTool
from tools.log_custom import setup_logging

setup_logging(logging.INFO)


def modify_jar(jar_name='nrljapplication.jar', target_ip="172.31.157.2"):
    """
    修改 jar 文件中的配置文件
    """

    # 提取文件夹
    extracted_path = "."

    # 要提取的文件列表
    files_to_extract = ['application.properties', 'application-druidmysql.properties', 'application-neo4j.properties']

    # 要替换的ip
    replace_ips = ['172.25.133.51', '172.25.133.52', '172.25.133.53', '172.25.133.55',
                   '172.31.144.5',
                   '172.25.131.104', '172.25.131.105', '172.25.131.106', '172.25.131.109']

    # 要替换的端口号
    replace_ports = {'3306': '3307',
                     '6379': '6479'}
    # 要替换的其它内容
    replace_texts = {'nrljdevdb2': 'nrljdevdb',
                     'ljdevuser2': 'ljdevuser',
                     'park_json_receive': 'backTopic',
                     'parkJsonReceiveConsumer': 'admin',
                     'parkJsonReceiveC-gzwl': 'admin-secret',
                     'park_vehicle_handle_json': 'backGroup'}

    # 更新包文件夹,先备份jar包为jar_bak
    target_file = FileTool.get_lianji_dir() / jar_name
    if not os.path.exists(target_file):
        logging.error(f"{target_file}不存在！,请将 nrljapplication.jar 放入此文件夹下")
        return

    # 1 依次提取指定文件
    with zipfile.ZipFile(jar_name, 'r') as jar:
        for file in files_to_extract:
            if file in jar.namelist():
                jar.extract(file, path=extracted_path)
            else:
                logging.error(f"{file} 不存在于 JAR 文件中")

    # 2 修改配置文件
    hostcmd = HostCmdTool()
    for replaced_ip in replace_ips:
        command = f"sd {replaced_ip} {target_ip} {extracted_path}/*"
        hostcmd.run_sh(command)
        command = f"grep -Iirs 172 {replaced_ip}"
        hostcmd.run_sh(command)

    for port, new_port in replace_ports.items():
        command = f"sd {port} {new_port} {extracted_path}/*"
        hostcmd.run_sh(command)
        command = f"grep -Iirs {port} {extracted_path}"
        hostcmd.run_sh(command)

    for text, new_text in replace_texts.items():
        command = f"sd {text} {new_text} {extracted_path}/*"
        hostcmd.run_sh(command)
        command = f"grep -Iirs {text} {extracted_path}"
        hostcmd.run_sh(command)

    # 3 替换配置文件
    # zip -u mytxt.zip t3.txt 添加或替换t3.txt
    # zip -f mytxt.zip t3.txt 替换t3.txt，如果不存在，不做操作
    command = f"cp -a {jar_name} {jar_name}_bak"
    hostcmd.run_sh(command)
    for f in files_to_extract:
        command = f"zip -u {jar_name} {extracted_path}/{f}"
        hostcmd.run_sh(command)

    # 4 清理临时和备份文件
    for f in files_to_extract:
        os.remove(os.path.join(extracted_path, f))
    os.remove(os.path.join(extracted_path, f"{jar_name}_bak"))


# 示例调用
if __name__ == "__main__":
    modify_jar(target_ip="172.31.157.2")
